import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import '../../../../../lib_runtime/logger.dart';
import 'room_music_center_controller.dart';

class RoomMusicMineController extends GetxController {
  late RoomMusicCenterController centerController;
  final int pageSize = 20;
  int offset = 0;

  ///我的播放列表
  List<Music>? musicCollection;

  ///需要上传确认的文件
  List<UploadMusic> musicNeedUpload = [];
  RefreshController controller = RefreshController(initialRefresh: false);
  bool canLoadMore = false;

  RoomMusicMineController();

  @override
  void onInit() {
    super.onInit();
    centerController = Get.find<RoomMusicCenterController>();
  }

  @override
  void onReady() {
    super.onReady();
    refreshData();
  }

  refreshData() async {
    offset = 0;
    // var result = await RtcApi.instance.mineMusicList(offset, pageSize);
    // if (result.isSuccess) {
    //   List<pb.Music>? musics = result.data?.musics;
    //   if (musics?.isNotEmpty == true) {
    //     musicCollection =
    //         musics?.map((e) => Music.fromJson(jsonDecode(e.content))).toList();
    //   } else {
    //     musicCollection = [];
    //   }
    //   canLoadMore = (musicCollection?.length ?? 0) >= pageSize;
    // } else {
    //   showToast(result.errorMsg ?? T.current!.request_fail);
    // }
    // update();
    // controller.refreshCompleted();
  }

  loadData() async {
    offset = musicCollection?.length ?? 0;
    // var result = await RtcApi.instance.mineMusicList(offset, pageSize);
    // if (result.isSuccess) {
    //   List<pb.Music>? musics = result.data?.musics;
    //   if (musics?.isNotEmpty == true) {
    //     List<Music>? list =
    //         musics?.map((e) => Music.fromJson(jsonDecode(e.content))).toList();
    //     musicCollection?.addAll(list ?? []);
    //     canLoadMore = (list?.length ?? 0) >= pageSize;
    //   }
    // } else {
    //   showToast(result.errorMsg ?? T.current!.request_fail);
    // }
    controller.loadComplete();
    update();
  }

  addMusic(Music music) async {
    RLog.d('addMusic:${music.songCode}');
    musicCollection?.add(music);
    centerController.loadLocalPreloadedFile();
    update();
  }

  int get count => musicCollection?.length ?? 0;

  void playAll() async {
    if (musicCollection != null && count > 0) {
      List<Music> list = musicCollection!;
      centerController.playlist = list;
      Music first = list.first;
      MediaPlayerState state = await centerController.playState(first);
      if (state != MediaPlayerState.playerStatePlaying) {
        centerController.play(list.first);
      }
    }
  }
}

class UploadMusic {
  String path;
  int songCode;
  String? name;

  UploadMusic(this.path, this.songCode, {this.name});
}
